package main

import (
	"context"
	"fmt"
	"os"

	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/consumer"
	"github.com/apache/rocketmq-client-go/v2/primitive"
)

func main() {
	c, _ := rocketmq.NewPushConsumer(
		consumer.WithNameServer([]string{"127.0.0.1:9876"}),
		consumer.WithConsumerModel(consumer.Clustering),
		consumer.WithGroupName("OrderConsumerGroup"),
		consumer.WithRetry(2),
		consumer.WithMaxReconsumeTimes(2), // 设置最大重试次数
	)
	err := c.Subscribe("OrderTopicDead", consumer.MessageSelector{}, func(ctx context.Context,
		msgs ...*primitive.MessageExt) (consumer.ConsumeResult, error) {
		for i := range msgs {
			//panic("ces")
			orderID := string(msgs[i].Body)
			// 这里应该有查询订单状态的逻辑
			orderStatus := checkOrderStatus(orderID)
			if orderStatus == "UNPAID" {
				// 如果订单未支付，执行取消订单操作
				cancelOrder(orderID)
			}
		}
		return consumer.ConsumeSuccess, nil
	})
	if err != nil {
		fmt.Printf("subscribe error: %s\n", err.Error())
	}
	// Note: Start after subscribe
	err = c.Start()
	if err != nil {
		fmt.Printf("start consumer error: %s\n", err.Error())
		os.Exit(1)
	}
	defer c.Shutdown()
	select {}
}

func checkOrderStatus(orderID string) string {
	// 这里应该是查询数据库或者调用服务来获取订单状态
	// 为了示例，这里直接返回一个假的状态
	return "UNPAID"
}

func cancelOrder(orderID string) {
	// 这里应该是执行取消订单的逻辑
	// 例如更新数据库中的订单状态，或者调用其他服务
	fmt.Printf("cancel order: %s\n", orderID)
}
